export default {
  data () {
    return {
      error: null,
      rules: null
    };
  },
  created () {
    if (!this.rules) {
      this.rules = {};
    }
    let data = this.data;
    if (data) {
      for (let itemKey in data) {
        if (!this.rules[itemKey]) {
          this.rules[itemKey] = [];
        }
        this.rules[itemKey].push({
          validator: this.remoteValidatorInfo,
          trigger: 'blur'
        });
      }
    }
  },
  computed: {
    data: function () {
      if (this.dataItem) {
        return this[this.dataItem];
      }
    }
  },
  methods: {
    remoteValidatorInfo (rule, value, callback) {
      if (this.error && this.error[rule.field]) {
        let message = this.error[rule.field];
        if (message) {
          this.error[rule.field] = null;
          return callback(new Error(message));
        }
      }
      return callback();
    },
    remoteValidate (self, formName, postFnt) {
      return new Promise(function (resolve, reject) {
        self.$refs[formName].validate(async function (valid) {
          let remoteData;
          if (valid) {
            remoteData = await postFnt(self[self.dataItem]);
            if (!remoteData['success']) {
              self.error = remoteData['error'];
              self.$refs[formName].validate((valid) => {
              });
              reject(new Error('request error'));
            } else {
              resolve(remoteData['data']);
            }
          } else {
            reject(new Error('request error'));
          }
        });
      });
    }
  }
};
